package com.wgz.medicalmanagement.infrastructure.security;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * JWT认证过滤器，用于验证请求中的JWT令牌
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtils jwtUtils;
    private final JwtUserDetailsService userDetailsService;
    
    // 认证头和前缀
    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    private static final String TOKEN_PARAM = "auth_token";
    
    // 不需要过滤的静态资源路径前缀
    private static final List<String> IGNORE_PATHS = Arrays.asList(
        "/css/", "/js/", "/images/", "/fonts/", "/favicon.ico"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        try {
            // 获取JWT令牌
            String jwt = getJwtFromRequest(request);
            
            // 如果存在有效的JWT且安全上下文中没有认证信息
            if (StringUtils.hasText(jwt) && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 从JWT中获取用户名
                String username = jwtUtils.extractUsername(jwt);
                
                if (StringUtils.hasText(username)) {
                    // 加载用户详情
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    
                    // 验证JWT令牌
                    if (jwtUtils.validateToken(jwt, userDetails)) {
                        // 创建认证令牌并设置安全上下文
                        UsernamePasswordAuthenticationToken authentication = 
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
        } catch (Exception e) {
            // 捕获所有异常但不中断请求流程
            // 已移除权限限制，即使JWT处理失败，请求也应当继续
            log.debug("JWT认证过程中发生异常: {}", e.getMessage());
        }
        
        // 继续过滤链
        filterChain.doFilter(request, response);
    }

    /**
     * 获取是否应该忽略这个请求路径（不处理JWT）
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();
        return IGNORE_PATHS.stream().anyMatch(path::startsWith);
    }

    /**
     * 从请求中提取JWT令牌
     * 
     * @param request HTTP请求
     * @return JWT令牌，如果不存在则返回null
     */
    private String getJwtFromRequest(HttpServletRequest request) {
        // 1. 从授权头中获取
        String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER_PREFIX)) {
            return bearerToken.substring(7);
        }
        
        // 2. 从请求参数中获取
        String paramToken = request.getParameter(TOKEN_PARAM);
        if (StringUtils.hasText(paramToken)) {
            if (paramToken.startsWith(BEARER_PREFIX)) {
                return paramToken.substring(7);
            }
            return paramToken;
        }
        
        return null;
    }
} 